package o2o.web.actions.report;

import com.jinyou.utils.common.AjaxResult;
import com.jinyou.utils.common.JYMathDoubleUtils;
import com.jinyou.utils.common.ValidateUtil;
import o2o.cache.agent.CityAgentMemory;
import o2o.cache.order.OrderInfoMemory;
import o2o.cache.order.OrderPayMemory;
import o2o.cache.shop.ShopMemory;
import o2o.cache.shop.ShopTipMemory;
import o2o.cache.shop.ShopTipRelationMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.dao.PO.agent.CityAgent;
import o2o.dao.PO.order.ORDER_STATUS;
import o2o.dao.PO.order.OrderInfo;
import o2o.dao.PO.order.OrderPayInfo;
import o2o.dao.PO.report.ReportForm;
import o2o.company.model.ShopInfo;
import o2o.dao.PO.shop.ShopTip;
import o2o.dao.PO.user.UserInfo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pay.ChannelUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * create by yangtk
 * 2018/10/31
 * 报表
 */
@Controller
public class ReportFormAction {


    @RequestMapping("/get/report/form")
    @ResponseBody
    public String getReportForm(String token, String city, String agentIds, String tipIds, String shopIds, Long startTime, Long endTime, String timeSlot, Integer sortType) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (startTime == null) {
            return AjaxResult.errorResult("开始时间不能为空");
        }
        if (endTime == null) {
            return AjaxResult.errorResult("结束时间不能为空");
        }
        if (null == city) {
            return AjaxResult.errorResult("城市不能为空");
        }
//        String[] tempShopId = shopIds.split(",");
//        if (tempShopId.length < 1) {
//            return AjaxResult.errorResult("请选择店铺");
//        }

        // 所有的order信息
        Map<String, OrderInfo> map = OrderInfoMemory.getInstance().getAllMap();
        List<OrderInfo> orderInfoList = getAllAccord(map, startTime, endTime);
        // 时间隔断
        if (timeSlot != null && !timeSlot.equals("")) {
            String[] str = timeSlot.split("-");
            if (str.length != 2) {
                return AjaxResult.errorResult("时间段不匹配");
            }
            orderInfoList = getTimeSlot(orderInfoList, str[0], str[1]);
        }
        List<ReportForm> reportFormList = new ArrayList<>();
        // shopIds
        if (ValidateUtil.isNotNull(shopIds)) {
            // shop
            List<Long> list = getListIdByString(shopIds);
            if (!ValidateUtil.isAbsList(list)) {
                return AjaxResult.successResult(0, null);
            }
            List<ReportForm> reportFormByListShopId = getReportFormByListShopId(orderInfoList, list);
            if (ValidateUtil.isAbsList(reportFormByListShopId)) {
                reportFormList = reportFormByListShopId;
            }
        } else if (ValidateUtil.isNotNull(tipIds)) {
            // tip、
            List<Long> list = getListIdByString(tipIds);
            if (!ValidateUtil.isAbsList(list)) {
                return AjaxResult.successResult(0, null);
            }
            List<ReportForm> getReportFormByTipId = getReportFormByTipId(orderInfoList, list);
            if (ValidateUtil.isAbsList(getReportFormByTipId)) {
                reportFormList = getReportFormByTipId;
            }
        } else if (ValidateUtil.isNotNull(agentIds)) {
            //agent
            List<Long> list = getListIdByString(agentIds);
            if (!ValidateUtil.isAbsList(list)) {
                return AjaxResult.successResult(0, null);
            }
            List<ReportForm> getReportByAgentId = getReportByAgentId(orderInfoList, list);
            if (ValidateUtil.isAbsList(getReportByAgentId)) {
                reportFormList = getReportByAgentId;
            }
        } else {
            // 城市
            List<ReportForm> reportByCity = getReportByCity(city, orderInfoList);
            if (ValidateUtil.isAbsList(reportByCity)) {
                reportFormList = reportByCity;
            }
        }
        // 排序
        if (ValidateUtil.isNotNull(shopIds)) {
            if (sortType != null) {
                if (ValidateUtil.isAbsList(reportFormList) && reportFormList.size() > 1) {
//                    reportFormList.stream().sorted(Comparator.comparing(sortType == 1 ? ReportForm::getTerminal : ReportForm::getShopName));
                    Collections.sort(reportFormList, new Comparator<ReportForm>() {
                        @Override
                        public int compare(ReportForm o1, ReportForm o2) {
                            if (sortType == 1) {
                                return o1.getTerminal().compareTo(o2.getTerminal());
                            } else if (sortType == 2) {
                                return o1.getShopName().compareTo(o2.getShopName());
                            }
                            return 1;
                        }
                    });
                }
            }
        }
        return AjaxResult.successResult(reportFormList.size(), reportFormList);
    }

    // 类型转换
    private List<Long> getListIdByString(String temp) {

        List<Long> list = new ArrayList<>();
        String[] tempId = temp.split(",");
        if (tempId.length < 1) {
            return list;
        }
        for (String str : tempId) {
            if (str == null || str.equals("")) {
                continue;
            }
            Long shopId = null;
            try {
                shopId = Long.parseLong(str);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("报表类型转换错误");
            }
            if (shopId == null) {
                continue;
            }
            list.add(shopId);
        }
        return list;
    }


    // 过滤所有符合时间段的order
    private List<OrderInfo> getTimeSlot(List<OrderInfo> list, String s1, String s2) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
        List<OrderInfo> orderInfoList = new ArrayList<>();
        if (ValidateUtil.isAbsList(list)) {
            for (OrderInfo orderInfo : list) {
                if (orderInfo == null || orderInfo.getCreateTime() == null) {
                    continue;
                }
                String temp = dateFormat.format(new Date(orderInfo.getCreateTime())).replaceAll(":", "");
                try {
                    long L1 = Long.parseLong(s1.replaceAll(":", ""));
                    long L2 = Long.parseLong(s2.replaceAll(":", ""));
                    long L = Long.parseLong(temp);
                    if (L1 <= L && L2 >= L) {
                        orderInfoList.add(orderInfo);
                    }
                } catch (Exception e) {
                    System.out.println("类型转换错误");
                    e.printStackTrace();
                }

            }
        }
        return orderInfoList;
    }

    // 获取指定城市下
    private List<ReportForm> getReportByCity(String city, List<OrderInfo> orderInfoList) {
        // 获取指定城市下的所有店铺
        List<ReportForm> reportFormList = new ArrayList<>();
        List<CityAgent> agentIds = CityAgentMemory.getInstance().listOfCity(city);
        if (!ValidateUtil.isAbsList(agentIds)) {
            return reportFormList;
        }
//        if (!ValidateUtil.isAbsList(orderInfoList)) {
//            return reportFormList;
//        }
        List<Long> list = new ArrayList<>();
        for (CityAgent cityAgent : agentIds) {
            if (null == city) {
                continue;
            }
            if (ValidateUtil.isID(cityAgent.getId())) {
                list.add(cityAgent.getId());
            }
        }

        List<ReportForm> reportByAgentId = getReportByAgentId(orderInfoList, list);
        ReportForm reportForm = addReport(reportByAgentId, 0L, city);
        if (reportForm != null) {
            reportFormList.add(reportForm);
        }
        return reportFormList;
    }


    // 获取指定商圈
    private List<ReportForm> getReportByAgentId(List<OrderInfo> orderInfoList, List<Long> agentIds) {
        List<ReportForm> reportFormList = new ArrayList<>();
        // 没有商圈
        if (!ValidateUtil.isAbsList(agentIds)) {
            return reportFormList;
        }
        // 没有订单
//        if (!ValidateUtil.isAbsList(orderInfoList)) {
//            return reportFormList;
//        }
        for (Long l : agentIds) {
            if (!ValidateUtil.isID(l)) {
                continue;
            }
            // 由商圈获取楼层
            CityAgent cityAgent = CityAgentMemory.getInstance().getById(l);
            if (cityAgent == null) {
                continue;
            }
            List<Long> getTipIds = ShopTipRelationMemory.getInstance().getTipListByAgentId(l);
            List<ReportForm> getReportFormList = getReportFormByTipId(orderInfoList, getTipIds);
            ReportForm reportForm = addReport(getReportFormList, l, cityAgent.getName());
            if (reportForm != null) {
                reportFormList.add(reportForm);
            }
        }
        return reportFormList;
    }


    // 指定楼层
    private List<ReportForm> getReportFormByTipId(List<OrderInfo> orderInfoList, List<Long> tipIds) {
        List<ReportForm> reportFormList = new ArrayList<>();
        // 没有楼层
        if (tipIds == null || tipIds.size() < 1) {
            return reportFormList;
        }
        // 没有订单
//        if (!ValidateUtil.isAbsList(orderInfoList)) {
//            return reportFormList;
//        }
        // 由楼层获取店铺
        if (ValidateUtil.isAbsList(tipIds)) {
            for (Long l : tipIds) {
                if (!ValidateUtil.isID(l)) {
                    continue;
                }
                // 获取楼层下的
                ShopTip shopTip = ShopTipMemory.getInstance().getById(l);
                if (ValidateUtil.isNull(shopTip)) {
                    continue;
                }
                List<Long> shopListByTipId = ShopTipRelationMemory.getInstance().getShopListByTipId(l);
                List<ReportForm> getReportFormList = getReportFormByListShopId(orderInfoList, shopListByTipId);
                ReportForm reportForm = addReport(getReportFormList, l, shopTip.getName());
                if (reportForm != null) {
                    reportFormList.add(reportForm);
                }
            }
        }
        return reportFormList;
    }

    // 指定店铺集合
    private List<ReportForm> getReportFormByListShopId(List<OrderInfo> orderInfoList, List<Long> shopIds) {
        List<ReportForm> reportFormList = new ArrayList<>();
        if (shopIds == null || shopIds.size() < 1) {
            return reportFormList;
        }

//        if (!ValidateUtil.isAbsList(orderInfoList)) {
//            return reportFormList;
//        }
//        List<ReportForm> reportFormList = new ArrayList<>();
        if (ValidateUtil.isAbsList(shopIds)) {
            for (Long l : shopIds) {
                if (!ValidateUtil.isID(l)) {
                    continue;
                }
                ReportForm reportForm = getReportFormByShopId(orderInfoList, l);
                if (reportForm == null) {
                    continue;
                }
                reportFormList.add(reportForm);
            }
        }
        return reportFormList;
    }

    // 计算
    private ReportForm addReport(List<ReportForm> reportFormList, Long id, String name) {
        long alipayCount = 0L;
        long wxCount = 0L;
        long ziQuCount = 0l;
        long postCount = 0L;
        long balanceCount = 0L;
        double alipayMoney = 0.0d;
        double wxMoney = 0.0d;
        double postMoney = 0.0d; // 抽成
        double shopMoney = 0.0d; // 抽成
        double balanceMoney = 0.0d;
        double deliveryPrice = 0.0d; // 配送费
        double paymentMoney = 0.0d; // 支付金额
        double settlementMoney = 0.0d;
        if (ValidateUtil.isAbsList(reportFormList)) {
            for (ReportForm reportForm : reportFormList) {
                if (null == reportForm) {
                    continue;
                }
                // zhif
                alipayCount += (reportForm.getAlipayCount() != null ? reportForm.getAlipayCount() : 0);
                wxCount += (reportForm.getWxCount() != null ? reportForm.getWxCount() : 0);
                ziQuCount += (reportForm.getZiQuCount() != null ? reportForm.getZiQuCount() : 0);
                postCount += (reportForm.getPostCount() != null ? reportForm.getPostCount() : 0);
                balanceCount += (reportForm.getBalanceCount() != null ? reportForm.getBalanceCount() : 0);
                alipayMoney = JYMathDoubleUtils.add(alipayMoney, reportForm.getAlipayMoney() != null ? reportForm.getAlipayMoney() : 0.0d);
                wxMoney = JYMathDoubleUtils.add(wxMoney, reportForm.getWxMoney() != null ? reportForm.getWxMoney() : 0.0d);
                postMoney = JYMathDoubleUtils.add(postMoney, reportForm.getPostMoney() != null ? reportForm.getPostMoney() : 0.0d);
                deliveryPrice = JYMathDoubleUtils.add(deliveryPrice, reportForm.getDeliveryPrice() != null ? reportForm.getDeliveryPrice() : 0.0d);
                shopMoney = JYMathDoubleUtils.add(shopMoney, reportForm.getShopMoney() != null ? reportForm.getShopMoney() : 0.0d);
                paymentMoney = JYMathDoubleUtils.add(paymentMoney, reportForm.getPaymentMoney() != null ? reportForm.getPaymentMoney() : 0.0d);
                balanceMoney = JYMathDoubleUtils.add(balanceMoney, reportForm.getBalanceMoney() != null ? reportForm.getBalanceMoney() : 0.0d);
                settlementMoney = JYMathDoubleUtils.add(settlementMoney, reportForm.getSettlementMoney() != null ? reportForm.getSettlementMoney() : 0.0d);
            }
        }
        ReportForm reportForm = new ReportForm();
        reportForm.setShopId(id);
        reportForm.setShopName(name);
        reportForm.setAlipayCount(alipayCount);
        reportForm.setAlipayMoney(alipayMoney);
        reportForm.setPostCount(postCount);
        reportForm.setPostMoney(postMoney);
        reportForm.setDeliveryPrice(deliveryPrice);
        reportForm.setWxCount(wxCount);
        reportForm.setWxMoney(wxMoney);
        reportForm.setZiQuCount(ziQuCount);
        reportForm.setBalanceCount(balanceCount);
        reportForm.setBalanceMoney(balanceMoney);
        reportForm.setShopMoney(shopMoney);
        // 目前没有余额支付 暂时先不做处理
        reportForm.setPaymentMoney(paymentMoney);
        reportForm.setSettlementMoney(settlementMoney);
        return reportForm;
    }

    // 单店的
    private ReportForm getReportFormByShopId(List<OrderInfo> orderInfoList, Long shopId) {
        long alipayCount = 0L;
        long wxCount = 0L;
        long ziQuCount = 0l;
        long postCount = 0L;
        long balanceCount = 0L;
        double alipayMoney = 0.0d;
        double wxMoney = 0.0d;
        double postMoney = 0.0d; // 抽成
        double balanceMoney = 0.0d;
        double shopMoney = 0.0d; // 抽成
        double deliveryPrice = 0.0d; // 配送费
        double paymentMoney = 0.0d; // 支付金额
        double settlementMoney = 0.0d;
        ReportForm reportForm = new ReportForm();
        if (shopId == null) {
            return null;
        }
        ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
        if (shopInfo == null) {
            return null;
        }
        if (ValidateUtil.isAbsList(orderInfoList)) {
            for (OrderInfo orderInfo : orderInfoList) {
                if (orderInfo == null) {
                    continue;
                } else {
                    if (orderInfo.getShopId() == shopId) {
                        // 是店铺的
                        // duiying zhidu
//                        OrderPayInfo orderPayInfo = OrderPayMemory.getInstance().get(orderInfo.getOrderNo());
//                        if(orderInfo == null){
//                            continue;
//                        }
                        //
//                        if(orderPayInfo.getIsPaid() == 0) {
//                            continue;
//                        }

                        //店铺实际收入金额
                        OrderPayInfo orderPayInfo = OrderPayMemory.getInstance().get(orderInfo.getOrderNo());
                        if (null == orderPayInfo || orderPayInfo.getIsPaid() == 0) {
                            continue;
                        }
                        String payType = orderInfo.getPayType();
                        if (payType == null) {
                            continue;
                        }
                        // 店铺抽成
                        shopMoney = JYMathDoubleUtils.add(shopMoney, orderPayInfo.getShopMoney() == null ? 0.0d : orderPayInfo.getShopMoney());
                        // 骑手抽成
                        postMoney = JYMathDoubleUtils.add(postMoney, orderPayInfo.getPostmanMoney() == null ? 0.0d : orderPayInfo.getPostmanMoney());

                        if (payType.contains(ChannelUtils.alipay)) {
                            // 支付宝
                            alipayCount++;
                            alipayMoney = JYMathDoubleUtils.add(alipayMoney, orderInfo.getTotalPrice());
                        } else if (payType.contains(ChannelUtils.wx)) {
                            // 微信
                            wxCount++;
                            double s = orderInfo.getTotalPrice();
                            wxMoney = JYMathDoubleUtils.add(wxMoney, orderInfo.getTotalPrice());
//                             += orderInfo.getTotalPrice();
                        } else {
                            // 其他  暂时标记为余额
                            balanceCount++;
                            balanceMoney = JYMathDoubleUtils.add(balanceMoney, orderInfo.getTotalPrice());
                        }
                        // 自提
                        if (orderInfo.getIsZiQu() == 1) {
                            // 自取
                            ziQuCount++;
                        } else {
                            // 配送
                            if (shopInfo.getIsSelfPost() == 0) {
                                postCount++;
                                // 配送费
                                deliveryPrice = JYMathDoubleUtils.add(deliveryPrice, (orderInfo.getDeliveryPrice() != null ? orderInfo.getDeliveryPrice() : 0.0d));
                            }
                        }
                    } else {
                        continue;
                    }
                }
            }
        }
        reportForm.setTerminal(shopInfo.getTerminal());
        reportForm.setShopId(shopId);
        reportForm.setShopName(shopInfo.getShopName());
        reportForm.setAlipayCount(alipayCount);
        reportForm.setAlipayMoney(alipayMoney);
        reportForm.setPostCount(postCount);
        reportForm.setDeliveryPrice(deliveryPrice);
        reportForm.setPostMoney(postMoney);
        reportForm.setWxCount(wxCount);
        reportForm.setWxMoney(wxMoney);
        reportForm.setZiQuCount(ziQuCount);
        reportForm.setBalanceCount(balanceCount);
        reportForm.setBalanceMoney(balanceMoney);
        reportForm.setPaymentMoney(JYMathDoubleUtils.add(wxMoney, alipayMoney));
        reportForm.setShopMoney(shopMoney);
        // 目前没有余额支付 暂时先不做处理
        reportForm.setSettlementMoney(JYMathDoubleUtils.sub(JYMathDoubleUtils.sub(JYMathDoubleUtils.add(wxMoney, alipayMoney), postMoney), shopMoney));
        return reportForm;
    }

    private Map<String, String> getAssistantMap(List<OrderPayInfo> list) {
        Map<String, String> map = new HashMap<>();
        if (ValidateUtil.isAbsList(list)) {
            //
            for (OrderPayInfo orderPayInfo : list) {
                if (orderPayInfo == null) {
                    continue;
                }
                // 支付
                if (orderPayInfo.getIsPaid() == 1) {

                } else {
                    continue;
                }
                map.put(orderPayInfo.getOrderNo(), orderPayInfo.getPayType());
            }
        }
        return map;
    }

    private List<OrderInfo> getAllAccord(Map<String, OrderInfo> map, Long startTime, Long endTime) {
        List<OrderInfo> orderInfoList = new ArrayList<>();
        if (null == map) {
            return orderInfoList;
        }
        for (OrderInfo orderInfo : map.values()) {
            if (orderInfo == null) {
                continue;
            }
            if (orderInfo.getOrderStatus() == ORDER_STATUS.OVER
                    || orderInfo.getOrderStatus() == ORDER_STATUS.POSTMAN_FINISH
                    ) {
                // 订单已经完成
            } else {
                continue;
            }
            // 时间验证
            if (orderInfo.getCreateTime() == null) {
                continue;
            } else {
                if (orderInfo.getCreateTime() >= startTime && orderInfo.getCreateTime() <= endTime) {

                } else {
                    continue;
                }
            }
            // 支付？？
            if (orderInfo.getIsPaid() != null && orderInfo.getIsPaid() == 1) {

            } else {
                continue;
            }
            orderInfoList.add(orderInfo);
        }
        return orderInfoList;
    }
}
